import { Component } from '@angular/core';
import {  NavController, NavParams, LoadingController, ToastController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { BaseUI } from '../../common/baseui';
import { RestProvider } from '../../providers/rest/rest';
import { HeadfacePage } from '../headface/headface';
/**
 * Generated class for the UserPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */


@Component({
  selector: 'page-user',
  templateUrl: 'user.html',
})
export class UserPage extends BaseUI {
  headface: string;
  nickname: string = "加载中";
  errorMessage: any;
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private storage: Storage,
    private loadCtrl: LoadingController,
    private rest: RestProvider,
    private toastCtrl: ToastController) {
    super();
  }

  ionViewDidEnter() {
    this.loadUserPage();
  }
  loadUserPage() {
    this.storage.get('UserId').then((val) => {
      if (val != null) {
        //加载用户数据
        var loading = super.showLoading(this.loadCtrl, "加载中...");
        this.rest.getUserInfo(val)
          .subscribe(userinfo => {
            this.nickname = userinfo["UserNickName"];
            this.headface = userinfo["UserHeadface"] + "?" + (new Date()).valueOf();
          }, error => this.errorMessage = <any>error);

        loading.dismiss();
      }
    })
  }
  updateNickName() {
    this.storage.get("UserId").then((val) => {
      if (val != null) {
        var loading = super.showLoading(this.loadCtrl, "加载中...");
        this.rest.updateNickName(val, this.nickname)
          .subscribe(f => {
            if (f["Status"] == "OK") {
              loading.dismiss();
              super.showToast(this.toastCtrl, "昵称修改成功");
            }else{
              loading.dismiss();
              super.showToast(this.toastCtrl, f["StatusContent"]);
            }
          },error => this.errorMessage = <any>error);
      }
    })
  }
  logOut(){
    this.storage.remove('UserId');
    this.navCtrl.pop();
  }

  goHeadFacePage(){
    this.navCtrl.push(HeadfacePage);
  }
}
